﻿using System;
using System.Collections;
using System.Xml;
using InfoJetSoft.Service.Entity;
using InfoJetSoft.Service.Util;

namespace InfoJetSoft.Service.Worker
{
	
	class XSNViewFormatTableWorker
	{
		//格式化视图中的Table绑定.
		//主要就是给xctName为RepeatingTable的tbody等元素赋予一个HtmlId,在客户端作xCollection操作时用作ContextId.
		public static void  formatTable(View view)
		{
			XmlElement root = view.Doc.DocumentElement;
			string xctName = NamespaceUtil.toFullName(view.XdPrefix, JetConstant.XD_xctname);
			string ifName = NamespaceUtil.toFullName(view.XslPrefix, "if" );
			//在Onkostendeclaratie.xsn中出现过repeatingtable.
			string tbodyFilter = "//*[@" + xctName + "='RepeatingTable' or @" + xctName + "='repeatingtable']";
			string foreachFilter = ".//" + NamespaceUtil.toFullName(view.XslPrefix, "for-each");
			XmlNodeList tbodyList = DOMUtil.selectNodes(root, tbodyFilter, 0, view.NsResolver);
			foreach (XmlNode tbodyNode in tbodyList)
			{
				XmlNodeList foreachList = DOMUtil.selectNodes(tbodyNode, foreachFilter, 0, view.NsResolver);
				foreach (XmlElement foreachElement in foreachList)
				{
					//将xslt for-each中的select表达示转换为binding,这样每个tbody都将获得一个Id.
					//这个Id的主要作用是在Table中添加删除行操作时,将作为contextId使用.
					string binding = getForeachSelectBinding(view, foreachElement);

					XmlNodeList trElementList = foreachElement.SelectNodes( ".//tr" );
					foreach (XmlElement trElement in trElementList)
					{
						trElement.SetAttribute(JetConstant.HTML_id, binding);
					}

					//收集Table上的ConditionFormat,ConditionFormat是IsServerNode判断的一个项目.
					XmlElement ifElement = (XmlElement)DOMUtil.selectANode( foreachElement, ifName, view.NsResolver );
					if( ifElement != null )
					{
						string test = ifElement.GetAttribute( "test" );
						if( view.Manifest.ConditionFormatTestList == null )
						{
							view.Manifest.ConditionFormatTestList = new ArrayList();
						}
						view.Manifest.ConditionFormatTestList.Add( test );
					}
				}
			}
		}
		
		//将for-each的select表达示转换为JetId的binding表达示.
		private static string getForeachSelectBinding(View view, XmlElement foreachElement)
		{
			string select = foreachElement.GetAttribute("select");
			if (select.Length <= 0)
			{
				throw new InfoJetException("for-each no attribute select", "XVFT01");
			}
            //CID 0714 //2010.11.29 //Begin
			string binding = DOMUtil.getSectionBindingExpr( view, select );
            //CID 0714 //2010.11.29 //End
			return binding;
		}
	}
}